/**
	Copyright (c) 2011 ATTi 
	All rights reserved.
	Author: Michael Shu
	Purpose : Copy from owner's info into case fields.
	Project : CCIR, CCOOR
	Date: 1/21/2011
*/

public without sharing class CaseFieldsUpdateFromOwnerHelper {
	private static set<ID> caseRTIds;
	public static String User_Prefix = GeneralConstants.User_Prefix;
	public static String Queue_Prefix = GeneralConstants.Queue_Prefix;
	
	public static set<ID> getCaseRTIds(){
		if(caseRTIds == null){
			caseRTIds = GeneralConstants.getRecordTypeIdsByNames('Case', GeneralConstants.RT_CCIR);		
		}
		return caseRTIds;
	}
	
	public static void setWhenCaseOwnerChange(list<Case> cases){
		set<ID> oIds = new set<ID>();
		set<ID> qIds = new set<ID>();
		for(Case c : cases){
			String tPrefix = String.Valueof(c.OwnerId).subString(0,3);
			if(tPrefix == User_Prefix){
				oIds.add(c.OwnerId);
			}else if(tPrefix == Queue_Prefix){
				qIds.add(c.OwnerId);
			}
		}
		map<ID, User> users;
		map<ID, Group> queues;
		if(!oIds.isEmpty()){
			users = new map<ID, User>([select Cycle_Team__c, UserRole.Name, Profile.Name from User where Id IN: oIds]);
		}
		if(!qIds.isEmpty()){
			queues = new map<ID, Group>([select Name from Group where Id IN: qIds and Type = 'Queue']);
		}
		for(Case c : cases){
			if(users != null && users.containsKey(c.OwnerId)){
				c.Owner_Role__c = users.get(c.OwnerId).UserRole.Name + ';' + users.get(c.OwnerId).Profile.Name;
				c.Cycle_Team__c = users.get(c.OwnerId).Cycle_Team__c;
				if(c.Cycle_Team__c != null && c.Initial_Team__c == null){ 
					c.Initial_Team__c = c.Cycle_Team__c;
				}
			}else{
				c.Owner_Role__c = null;
				c.Cycle_Team__c = null;
			}
			if(queues != null && queues.containsKey(c.OwnerId)){
				c.IOG_Queue_Owner__c = queues.get(c.OwnerId).Name;
			}else if(c.IOG_Queue_Owner__c == null){
				c.IOG_Queue_Owner__c = c.Cycle_Team__c;
			}
		}
	}
	
	public static void setPrevOwnerAndLastQueueOwner(Case c, Case oldcs){
		if(oldcs != null){
			String tPrefixOld = String.Valueof(oldcs.OwnerId).subString(0,3);
			if(oldcs.OwnerId != c.OwnerId && tPrefixOld == User_Prefix){
				c.Previous_Owner__c = oldcs.OwnerId;
			}
		}
		String tPrefixNew = String.Valueof(c.OwnerId).subString(0,3);
		if(tPrefixNew == Queue_Prefix){
			c.Last_Queue_Owner__c = c.OwnerId;
		}
	}
}